//
//  C3Hydrogen.m
//  精通Objective-C
//
//  Created by 花强 on 2017/11/6.
//  Copyright © 2017年 花强. All rights reserved.
//

#import "C3Hydrogen.h"
#import "C3HydrogenHelper.h"

@implementation C3Hydrogen{
@private C3HydrogenHelper * _helper;
}

-(id)initWithNeutrons:(NSUInteger)neutrons{
    if (self = [super init]) {
        _chemicalElement = @"Hydrogen";
        _atomicSymbol = @"H";
        _protons = 1;
        _neutrons = neutrons;
        
        //为实现消息转发机制创建辅助对象
        _helper = [[C3HydrogenHelper alloc] init];
    }
    return self;
}

+(id)hydrogenWithNeutrons:(NSUInteger)neutrons{
    return [[[self class] alloc] initWithNeutrons:neutrons];
}

//快速转发
-(id)forwardingTargetForSelector:(SEL)aSelector{
    if ([_helper respondsToSelector:aSelector]) {
        return _helper;
    }
    return nil;
}

//标准转发
/*
 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
 这个方法返回了对应的对象才会进
 - (void)forwardInvocation:(NSInvocation *)anInvocation
 */
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    NSMethodSignature* signature = [super methodSignatureForSelector:aSelector];
    if (signature==nil) {
        signature = [_helper methodSignatureForSelector:aSelector];
    }
    NSUInteger argCount = [signature numberOfArguments];
    for (NSInteger i=0 ; i<argCount ; i++) {
        NSLog(@"%s" , [signature getArgumentTypeAtIndex:i]);
    }
    NSLog(@"returnType:%s ,returnLen:%ld" , [signature methodReturnType] , [signature methodReturnLength]);
    NSLog(@"signature:%@" , signature);
    return signature;
}
-(void)forwardInvocation:(NSInvocation *)anInvocation{
    if ([_helper respondsToSelector:[anInvocation selector]]){
        
        [anInvocation invokeWithTarget:_helper];
    }else{
        [super forwardInvocation:anInvocation];
    }
}

@end
